package com.kehongborui.fliggy.util;

import com.sun.mail.util.MailSSLSocketFactory;
import org.apache.log4j.Logger;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;
import java.security.GeneralSecurityException;
import java.util.Properties;

/**
 * @author zhang peng yang ming
 * @CopyRight (C) http://www.csdn.com
 * @brief
 * @email 122162005@qq.com
 * @date 2018-08-31
 */
public class MailUtil {
    private static Logger log = Logger.getLogger(MailUtil.class);
    /**
     * 向注册用户发送认证邮件
     * @param addressee 收件人
     * @param code 激活验证码
     */
    public static void sendEmail(String addressee, String code) throws MessagingException, GeneralSecurityException {

        String from = "1069711263@qq.com";// 发件人电子邮箱
        String host = "smtp.qq.com"; // 指定发送邮件的主机smtp.qq.com(QQ)|smtp.163.com(网易)
        Properties properties = System.getProperties();// 获取系统属性

        properties.setProperty("mail.smtp.host", host);// 设置邮件服务器
        properties.setProperty("mail.smtp.auth", "true");// 打开认证

        //QQ邮箱需要下面这段代码，163邮箱不需要
        MailSSLSocketFactory sf = new MailSSLSocketFactory();
        sf.setTrustAllHosts(true);
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);


        // 1.获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication("1069711263@qq.com", "csbndfhaavtqbbac"); // 发件人邮箱账号、授权码
            }
        });

        // 2.创建邮件对象
        Message message = new MimeMessage(session);
        // 2.1设置发件人
        message.setFrom(new InternetAddress(from));
        // 2.2设置接收人
        message.addRecipient(Message.RecipientType.TO, new InternetAddress(addressee));
        // 2.3设置邮件主题
        message.setSubject("飞猪账号激活");
        // 2.4设置邮件内容
        String content = "<html><head></head><body><h1>这是一封激活邮件,激活请点击以下链接</h1><h3><a href='http://localhost:8080/RegisterDemo/ActiveServlet?code="
                + code + "'>http://www.flyy.com:8080/reg/active?code=" + code
                + "</href></h3></body></html>";
        message.setContent(content, "text/html;charset=UTF-8");
        // 3.发送邮件
        Transport.send(message);
        log.info("邮件成功发送!");
    }

    public static void main(String[] args) {
        try {
            sendEmail("1069711263@qq.com", "hello，jianhui:你好，建辉");
        } catch (MessagingException e) {
            e.printStackTrace();
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
    }
}
